<?php

class dbHandler implements dbHandlerInterface {
	private $aether;
	private $debug;
	private $config;
	private $errorHandler;
	private $handler;

	public function __construct($aether) {
		//Set the reference variables
		$this->aether = $aether;
		$this->debug = $aether->debug;
		$config = $this->aether->config;
		$this->errorHandler = $aether->errorHandler;
		
		//Connect to the database
		if(!$this->handler = mysql_connect($config->get('database', 'host'),$config->get('database', 'user'),$config->get('database', 'pass'))) {
			$this->errorHandler->trigger('mysqlConnectError', array('host' => $config->get('database', 'host'), 'user' => $config->get('database', 'user'), 'pass' => $config->get('database', 'pass'), 'error' => mysql_error()));
		}
		if(!mysql_select_db($config->get('database', 'name'),$this->handler)) {
			$this->errorHandler->trigger('mysqlSelectDbError', array('database' => $config->get('database', 'name')));
		}
	}
	
	function query($query, $fatalError = true) {
		$this->debug->write('Running query: "'.$query.'"');
		$result = mysql_query($query,$this->handler); //Run query
		if($result===false) { //Return error if there is one
			$this->errorHandler->trigger('mysqlError', array('query' => $query, 'error' => mysql_error($this->handler)));
		}
		return $result;
	}

	function insertId() {
		return mysql_insert_id($this->handler);
	}

	function nextAssoc($results) {
		return mysql_fetch_assoc($results);
	}

	function nextNumeric($results) {
		return mysql_fetch_row($results);
	}

	function error() {
		return mysql_error($this->handler);
	}
	
	function __destruct() {
		if($this->handler) {
			mysql_close($this->handler); //Close MySQL connection
		}
	}
};

?>
